import { useCallback, useRef, useEffect, useState } from 'react';
import ResponsiveGridLayout, { type Layout } from 'react-grid-layout';
import { useDrop } from 'react-dnd';
import type { GridWidget } from '../types/prevViewTypes';
import * as echarts from 'echarts';
import BigNumber from 'bignumber.js';
import CommonChart from './chartComponents/CommomChart';

// 定义数据项类型接口
interface EchartDataItem {
  xTime: string;
  yValue: string; // 原始数据为字符串类型的数值
}

// 画布组件属性接口
interface CanvasProps {
  layout: Layout[];
  widgets: Record<string, GridWidget>; // 使用Record更规范
  onLayoutChange: (layout: Layout[]) => void;
  onAddWidget: (widget: GridWidget, x: number, y: number) => void;
}

/**
 * 生成ECharts配置项的钩子
 * @returns 接收数据并返回ECharts配置的函数
 */
const useOption = () => {
  // 明确返回函数的参数和返回值类型
  return (data: EchartDataItem[]): echarts.EChartsOption => ({
    color: ['#ffffff'],
    title: {
      text: '图表y轴时间',
      textAlign: 'left',
      textStyle: {
        color: '#ffffff',
        fontSize: 12,
        fontWeight: 'lighter',
        fontFamily: 'Lato',
      },
    },
    grid: {
      left: '2%',
      right: '3%',
      top: '15%',
      bottom: '2%',
      containLabel: true,
    },
    xAxis: [
      {
        axisLine: {
          lineStyle: {
            color: '#ffffff',
            width: 1,
          },
        },
        data: data.map((item) => item.xTime),
        axisLabel: {
          formatter: (value: string) => value,
        },
        boundaryGap: false,
      },
    ],
    yAxis: [
      {
        position: 'left',
        type: 'value',
        scale: true,
        axisLine: {
          lineStyle: {
            color: '#ffffff',
            width: 1,
          },
        },
        splitLine: {
          lineStyle: {
            color: '#ffffff',
            width: 0.5,
            opacity: 0.2,
          },
        },
        axisLabel: {
          formatter: (value: number) => new BigNumber(value).toString(),
        },
        boundaryGap: ['5%', '2%'],
      },
      {
        position: 'right',
        type: 'value',
        axisLine: {
          lineStyle: {
            color: '#ffffff',
            width: 1,
          },
        },
      },
    ],
    series: [
      {
        name: '测试图表',
        type: 'line',
        yAxisIndex: 0,
        lineStyle: {
          color: '#ffffff',
          width: 1,
        },
        symbol: 'none',
        data: data.map((item) => new BigNumber(item.yValue).toNumber()),
      },
    ],
  });
};

// 明确图表数据类型
const echartData: EchartDataItem[] = [
  { xTime: '2020-01-01', yValue: '1500' },
  { xTime: '2020-01-02', yValue: '5220' },
  { xTime: '2020-01-03', yValue: '4000' },
  { xTime: '2020-01-04', yValue: '3500' },
  { xTime: '2020-01-05', yValue: '7800' },
];

const Canvas = ({ layout, widgets, onLayoutChange, onAddWidget }: CanvasProps) => {
  const canvasRef = useRef<HTMLDivElement>(null);
  const [containerWidth, setContainerWidth] = useState(1200); // 动态容器宽度
  const parseOption = useOption();

  // 处理拖放逻辑
  const [{ isOver }, dropRef] = useDrop({
    accept: 'widget',
    drop: (item: GridWidget, monitor) => {
      if (!canvasRef.current) return;

      // 安全处理鼠标位置（避免null断言）
      const clientOffset = monitor.getClientOffset();
      if (!clientOffset) return;

      const { x, y } = clientOffset;
      const clientRect = canvasRef.current.getBoundingClientRect();
      const relativeX = x - clientRect.left;
      const relativeY = y - clientRect.top;

      onAddWidget(item, relativeX, relativeY);
    },
    collect: (monitor) => ({
      isOver: monitor.isOver(),
    }),
  });
  const innerDivRef = useRef<HTMLDivElement>(null);

  // 监听容器宽度变化，实现响应式
  useEffect(() => {
    if (innerDivRef.current) {
      dropRef(innerDivRef.current);
    }
    const handleResize = () => {
      if (canvasRef.current) {
        setContainerWidth(canvasRef.current.offsetWidth);
      }
    };

    // 初始化宽度
    handleResize();
    // 监听窗口大小变化
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, [dropRef]);

  // 布局变化处理（优化依赖项）
  const onLayoutChangeHandler = useCallback(
    (newLayout: Layout[]) => {
      onLayoutChange(newLayout);
    },
    [onLayoutChange]
  );

  return (
    <div ref={innerDivRef} style={{ width: '100%', height: '100%' }}>
      {/* 绑定拖放ref */}
      <ResponsiveGridLayout
        className="layout"
        layout={layout}
        rowHeight={30}
        width={containerWidth} // 使用动态宽度
        cols={12}
        onLayoutChange={onLayoutChangeHandler}
        isResizable={true}
        isDraggable={true}
        margin={[10, 10]}
        containerPadding={[10, 10]}
      >
        {/* 使用Object.entries优化遍历 */}
        {Object.entries(widgets).map(([key, widget]) => (
          <div key={key} data-grid={layout.find((item) => item.i === key)}>
            <span>{widget.name}</span>
            <CommonChart
              option={parseOption(echartData)} // 修正多余参数问题
              notMerge
              lazyUpdate
              style={{ height: '180px', backgroundColor: '#6d5858ff' }}
            />
          </div>
        ))}
      </ResponsiveGridLayout>
    </div>
  );
};

export default Canvas;
